package com.moore.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.Base64;

public class AESUtils {
    private static final String ALGORITHM = "AES";
    private static final String KEY_FILE = "aes.key";

    // 生成密钥并保存到文件
    public static SecretKey generateAndSaveKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(256); // 选择密钥长度
        SecretKey key = keyGen.generateKey();
        saveKey(key);
        return key;
    }

    // 保存密钥到文件
    public static void saveKey(SecretKey key) throws Exception {
        byte[] encoded = key.getEncoded();
        try (FileOutputStream fos = new FileOutputStream(KEY_FILE)) {
            fos.write(encoded);
        }
    }

    // 从文件读取密钥
    public static SecretKey loadKey() throws Exception {
        File keyFile = new File(KEY_FILE);
        if (!keyFile.exists()) {
            return generateAndSaveKey();
        }
        byte[] encoded = new byte[(int) keyFile.length()];
        try (FileInputStream fis = new FileInputStream(keyFile)) {
            fis.read(encoded);
        }
        return new SecretKeySpec(encoded, ALGORITHM);
    }

    // 加密
    public static String encrypt(String data, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 解密
    public static String decrypt(String encryptedData, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData);
    }
}
